import 'package:flutter/material.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/model/knowledge_model.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'anchor_view.dart';

class AnchorBakingPage extends StatefulWidget {
  const AnchorBakingPage({Key? key}) : super(key: key);

  @override
  _AnchorBakingPageState createState() => _AnchorBakingPageState();
}

class _AnchorBakingPageState extends State<AnchorBakingPage>
    with AutomaticKeepAliveClientMixin {
  /// 下拉刷新控制器
  EasyRefreshController? _easyRefreshController;
  /// 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;
  /// 列表数组模型
  List<KnowledgeModel> _cookInfoList = KnowledgeModelList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String? errorMsg;

  // 获取数据
  Future _getRecommendData({bool replace = true}) async {
    try {
      Map<String, dynamic> result =
          await HttpService.getCookFoodData(offset: page*10);
      KnowledgeModelList knowledgeModelList =
          KnowledgeModelList.fromJson(result['data']);

      setState(() {
        page++;
        if (replace) {
          _cookInfoList = knowledgeModelList.list;
        } else {
          _cookInfoList.addAll(knowledgeModelList.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
  }

  @override
  void dispose() {
    _easyRefreshController!.dispose();
    _scrollController!.dispose();
    super.dispose();
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 1;
    await _getRecommendData();
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController!.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await _getRecommendData(replace: false);
    }
    // 结束加载
    _easyRefreshController!.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: EasyRefresh(
        // 开启首次加载刷新
        firstRefresh: true,
        // 加载时的loading
        // firstRefreshWidget: PageFeedBack(firstRefresh: true).build(),
        // 空视图、异常视图
        // emptyWidget: PageFeedBack(
        //   loading: loading,
        //   error: error,
        //   empty: _songList.isEmpty,
        //   errorMsg: errorMsg,
        //   onErrorTap: () => _easyRefreshController.callRefresh(),
        //   onEmptyTap: () => _easyRefreshController.callRefresh(),
        // ).build(),
        header: CustomHeaderView(),
        footer: CustomFooterView(),
        controller: _easyRefreshController,
        enableControlFinishRefresh: false,
        enableControlFinishLoad: true,
        onRefresh: _onRefresh,
        onLoad: _onLoad,
        child: ListView.builder(
            scrollDirection: Axis.vertical,
            itemCount: _cookInfoList.length,
            shrinkWrap: true, //增加
            itemBuilder: (BuildContext context, int index) {
              return AnchorView(model: _cookInfoList[index],);
            }),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive =>true;
}
